package com.jintoufs.web.action.customer;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Maps;
import com.jintoufs.dao.QueryFilters;
import com.jintoufs.dao.QueryRule;
import com.jintoufs.domain.auth.AuthImg;
import com.jintoufs.domain.common.xEditableItem;
import com.jintoufs.domain.constants.Constants;
import com.jintoufs.domain.customer.Customer;
import com.jintoufs.domain.customer.CustomerRole;
import com.jintoufs.domain.sys.Dictionary;
import com.jintoufs.domain.user.User;
import com.jintoufs.logAnnotation.SystemControllerLog;
import com.jintoufs.service.authImg.AuthImgService;
import com.jintoufs.service.customer.CustomerRoleService;
import com.jintoufs.service.customer.CustomerService;
import com.jintoufs.service.role.RoleService;
import com.jintoufs.service.sys.DictionaryService;
import com.jintoufs.service.user.PasswordHelper;
import com.jintoufs.service.user.UserService;
import com.jintoufs.util.CardCodeGenerator;
import com.jintoufs.util.valid.ValidUtil;
import com.jintoufs.util.ztree.TreeNode;
import com.jintoufs.web.action.support.JqgridPage;
import com.jintoufs.web.action.support.SupportAction;
import org.apache.poi.ss.formula.functions.T;
import org.cosmos.modules.web.msg.AjaxMsg;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * Created by zhx
 */
@Controller
@Scope("prototype")
@RequestMapping("/customer")
public class CustomerAction extends SupportAction {
    @Resource
    private CustomerService customerService;
    @Resource
    private CustomerRoleService customerRoleService;
    @Resource
    private DictionaryService dictionaryService;
    @Resource
    private PasswordHelper passwordHelper;
    @Resource
    private AuthImgService authImgService;

    @RequestMapping("/share-list")
    public String shareList(Integer type, Model model) {
        model.addAttribute("type", 1);
        return "supplier/user/share-list";
    }

    @RequestMapping("/customer-list")
    public String customerList(Integer type, Model model) {
        model.addAttribute("type", 2);
        return "supplier/user/customer-list";
    }


    @RequestMapping("/shop-manager-list")
    public String shopManagerList(Integer type, Model model) {
        model.addAttribute("type", 0);
        return "supplier/user/list";
    }

    @RequestMapping("/oper")
    @SystemControllerLog(description = "修改用户信息、基本信息、角色等")
    public void oper(HttpServletResponse response, String _id, String oper, Customer customer, String photo,String fileUrls) {
        AjaxMsg ajaxMsg = new AjaxMsg();
        try {
            switch (oper) {
                case "del":
                    String[] ids = _id.split(",");
                    for (String id : ids) {
                        customerService.delete(id);
                    }
                    break;
                case "edit":
                    Map<String, Object> param = new HashMap<>();
                    if (ValidUtil.isEmpty(customer.getUserName()) && !ValidUtil.isEmpty(customer.getRoleId())) {
                        customer.setUserName(customer.getMobilePhone());
                        customer.setType(0);
                        customer.setAuth("1");
                    }
                    if (ValidUtil.isEmpty(customer.getUserName())) {
                        param.put("id", customer.getId());
                    } else {
                        param.put("userName", customer.getUserName());
                    }
                    List<Customer> customers = customerService.queryByParams(param);
                    if (customers.size() > 1) {
                        ajaxMsg.setCode("500");
                        ajaxMsg.setDatas("服务器异常");
                    } else if (customers.size() == 1) {
                        Customer tmp = customers.get(0);
                        if (tmp.getId().equals(customer.getId())) {
                            if (tmp.getType()!=0&& !ValidUtil.isEmpty(customer.getRoleId())){
                                customer.setPassword(CardCodeGenerator.generateShortCode());
                                ArrayList<String> params = new ArrayList<String>();
                                params.add(customer.getPassword());
                                List<Dictionary> list = dictionaryService.getDicByKeyNo("CREATE_CUSTOEMER");
                                if (!list.isEmpty() && list.size() > 0) {
                                    int smsId = Integer.parseInt(list.get(0).getCaption().toString());
                                    customerService.sendSms(customer.getMobilePhone(), params, smsId);
                                }
                                passwordHelper.encryptPassword(customer);
                                customer.setType(0);
                            }
                            customer.setAuthType(Constants.CUSTOMER_AUTH_TYPE_B);
                            customerService.update(customer);
                            ajaxMsg.setCode("200");
                            ajaxMsg.setMessage("更新成功");
                        } else {
                            ajaxMsg.setCode("500");
                            ajaxMsg.setDatas("用户名已存在");
                        }
                    } else {
                        customerService.update(customer);
                        ajaxMsg.setCode("200");
                        ajaxMsg.setMessage("更新成功");
                    }
                    break;
                case "add":
                    customer.setPassword(CardCodeGenerator.generateShortCode());
                    customer.setCreateTime(new Date());
                    customer.setId(getUUID());
                    customer.setType(0);
                    customer.setAuth("1");
                    Customer tmp = customerService.add(customer);
                    if (tmp == null) {
                        ajaxMsg.setCode("500");
                        ajaxMsg.setMessage("添加失败，用户名重复");
                    } else {
                        ajaxMsg.setCode("200");
                        ajaxMsg.setMessage("添加成功");
                    }
                    break;
                default:
                    ajaxMsg.setCode("500");
                    ajaxMsg.setMessage("操作代码错误！系统只提供增加/修改/删除功能。");
                    break;
            }
            if("edit".equals(oper)||"add".equals(oper)){
                if("edit".equals(oper)){
                    authImgService.deleteWithCustomerIdAndCode(customer.getId(),"Qualification_certificate");
                }
                if(!"".equals(fileUrls)){
                    for (String url:fileUrls.split("___")){
                        AuthImg img = new AuthImg();
                        img.setCustomerId(customer.getId());
                        img.setCode("Qualification_certificate");
                        img.setPath(url);
                        img.setName("供应商资质证书");
                        authImgService.save(img,getUUID());
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            ajaxMsg.setCode("500");
            if (e instanceof DuplicateKeyException) {
                ajaxMsg.setMessage("此员工编号已存在！");
            } else {
                ajaxMsg.setMessage("程序出错，请联系管理员！");
            }
        }
        writeInfo(response, JSON.toJSONString(ajaxMsg));
    }

    @RequestMapping("/delete")
    @SystemControllerLog(description = "删除用户")
    public void delete(HttpServletResponse response, String id) {
        customerService.delete(id);
        writeInfo(response, JSON.toJSONString(new AjaxMsg()));
    }

    /**
     * input.do?id= 进入类目编辑页面 <br>
     * input.do 进入类目新增页面（不包含选中父类目）
     *
     * @param id    类目Id
     * @param model
     * @return vm/category/input.vm
     */
    @RequestMapping("input")
    public String input(String id, Model model) {
        Map<String, Object> result = Maps.newHashMap();
        String title;
        // 是否为编辑保存
        String isEdit;

        // 修改
        if (!ValidUtil.isEmpty(id)) {
            title = "修改用户";
            result = customerService.queryUserById(id);

            isEdit = "edit";
            Map<String,Object> param = Maps.newHashMap();
            param.put("customerId",id);
            param.put("code","Qualification_certificate");
            model.addAttribute("images", authImgService.queryByParam(param));
        } else {
            title = "新增用户";
            isEdit = "add";
        }

        List<Dictionary> statusList = dictionaryService.getDicByKeyNo("员工状态");
        List<xEditableItem> itemList = new ArrayList<>();
        for (
                Dictionary dic : statusList)

        {
            xEditableItem item = new xEditableItem();
            item.setValue(dic.getKeyValue());
            item.setText(dic.getCaption());
            itemList.add(item);
        }

        String roleId = "0";

        if (result != null && result.get("roleId") != null)

        {
            roleId = result.get("roleId").toString();
        }

        // 查询所有角色
        List<TreeNode> roleList = customerRoleService.getRoleMenu(roleId);
        model.addAttribute("roleTree", JSON.toJSONString(roleList));
        model.addAttribute("isEdit", isEdit);
        model.addAttribute("itemList", JSON.toJSONString(itemList));
        model.addAttribute("result", result);
        model.addAttribute("title", title);

        return "supplier/user/user-detail";
    }

    @RequestMapping("/query")
    @ResponseBody
    public JqgridPage query(int page, int rows, String sidx, String sord, String filters, Integer type) {
        PageHelper.startPage(page, rows);
        QueryFilters filters_ = null;
        if (filters == null || filters.trim().isEmpty()) {
            filters_ = new QueryFilters();
        } else {
            filters_ = JSON.parseObject(filters, QueryFilters.class);
        }
        QueryRule queryRule;
        if (type != null) {
            queryRule = new QueryRule();
            queryRule.setField("u.type");
            queryRule.setOp("eq");
            queryRule.setData(type.toString());
            filters_.getRules().add(queryRule);
        }
        filters_.setSidx(sidx);
        filters_.setSord(sord);
        List<Customer> list = customerService.getByFilter(filters_);
        // 用PageInfo对结果进行包装
        PageInfo pageInfo = new PageInfo(list);
        return new JqgridPage(pageInfo.getTotal(), pageInfo.getPages(), pageInfo.getPageNum(), pageInfo.getList());
    }

    @RequestMapping("/customerQuery")
    @ResponseBody
    public JqgridPage customerQuery(int page, int rows, String sidx, String sord, String filters, Integer type) {
        PageHelper.startPage(page, rows);
        boolean flag=true;
        QueryFilters filters_ = null;
        if (filters == null || filters.trim().isEmpty()) {
            filters_ = new QueryFilters();
        } else {
            filters_ = JSON.parseObject(filters, QueryFilters.class);
        }
        QueryRule queryRule;
        List<QueryRule> queryRules = filters_.getRules();
        if (queryRules.size()!=0){
            for (QueryRule queryRule1:queryRules){
                if ("u.type".equals(queryRule1.getField())){
                    flag=false;
                    switch (queryRule1.getData()){
                        case "是":queryRule1.setData("2");break;
                        case "否":queryRule1.setData("3");break;
                        default:queryRules.remove(queryRule1);break;
                    }
                }
            }
        }
        if (type != null&&flag) {
            queryRule = new QueryRule();
            queryRule.setField("u.type");
            if (2 != type) {
                queryRule.setOp("eq");
                queryRule.setData(type.toString());
            } else {
                queryRule.setOp("in");
                queryRule.setData("2,3");
            }
            filters_.getRules().add(queryRule);
        }
        filters_.setSidx(sidx);
        filters_.setSord(sord);
        List<Map<String, Object>> list = customerService.getByFilter2(filters_);
        // 用PageInfo对结果进行包装
        PageInfo pageInfo = new PageInfo(list);
        return new JqgridPage(pageInfo.getTotal(), pageInfo.getPages(), pageInfo.getPageNum(), pageInfo.getList());
    }

    /**
     * 初始化用户密码
     */
    @RequestMapping("/initPassword")
    @ResponseBody
    @SystemControllerLog(description = "初始化用户密码")
    public AjaxMsg initPassword(HttpServletRequest httpServletRequest ,String ids) {
        httpServletRequest.getParameter("id");
        AjaxMsg ajaxMsg = new AjaxMsg();
        if (!ValidUtil.isEmpty(ids)) {
                customerService.initPassword(ids);
        }
        ajaxMsg.setCode(AjaxMsg.SUCCESS);
        return ajaxMsg;
    }


    /**
     * 获取用户详细信息
     */
    @RequestMapping("/getDetail")
    @SystemControllerLog(description = "获取用户信息")
    public String getDetail(String id, Model model) {
        Map<String, Object> result = new HashMap<String, Object>();
        if (!ValidUtil.isEmpty(id)) {
            result = customerService.queryUserById(id);
        }
        model.addAttribute("result", result);
        model.addAttribute("isEdit", "view");
        model.addAttribute("title", "个人详细信息");
        return "supplier/user/user-detail";
    }


    @RequestMapping("/getUserByRole")
    @ResponseBody
    public List<Customer> getUserByRole(String roleName) {
        List<Customer> users = customerService.getUserByRoleName(roleName);
        return users;
    }

    /**
     * 修改用户密码
     */
    @RequestMapping("/modifyPwd")
    @ResponseBody
    @SystemControllerLog(description = "修改用户密码")
    public AjaxMsg modifyPwd(String username, String newPwd) {
        AjaxMsg ajaxMsg = new AjaxMsg();
        try {
            Customer user = null;
            Map<String, Object> params = Maps.newHashMap();
            params.put("userName", username);
            List<Customer> list = customerService.queryByParams(params);
            if (list != null && list.size() > 0) {
                user = list.get(0);
            }
            if (user != null) {
                user.setPassword(newPwd);
                passwordHelper.encryptPassword(user);
                customerService.update(user);
            }
            ajaxMsg.setCode(AjaxMsg.SUCCESS);
            ajaxMsg.setMessage("修改密码成功！");
        } catch (Exception e) {
            e.printStackTrace();
            ajaxMsg.setCode(AjaxMsg.FAILURE);
            ajaxMsg.setMessage("修改密码失败！");
        }
        return ajaxMsg;
    }

    @RequestMapping("/to-shop-manage")
    public AjaxMsg toShopManage(String id) {
        AjaxMsg ajaxMsg = new AjaxMsg();
        Map<String, Object> params = Maps.newHashMap();
        try {
            params.put("id", id);
            Customer tmp = customerService.queryByParams(params).get(0);
            params.clear();
            tmp.setPassword(CardCodeGenerator.generateRandomPassword());
            tmp.setType(0);
            params.put("userName", tmp.getMobilePhone());
            Integer num = customerService.queryByParams(params).size() + 1;
            if (num == 1) {
                tmp.setUserName(tmp.getMobilePhone());
            } else {
                tmp.setUserName(tmp.getMobilePhone() + "_" + num);
            }
            ArrayList<String> params2 = new ArrayList<String>();
            params2.add(tmp.getPassword());
            List<Dictionary> list = dictionaryService.getDicByKeyNo("CREATE_CUSTOEMER");
            if (!list.isEmpty() && list.size() > 0) {
                int smsId = Integer.parseInt(list.get(0).getCaption().toString());
                customerService.sendSms(tmp.getMobilePhone(), params2, smsId);
            }
            passwordHelper.encryptPassword(tmp);
            customerService.update(tmp);
            ajaxMsg.setMessage("用户名为:" + tmp.getUserName());
        } catch (Exception e) {
            ajaxMsg.setCode("500");
            ajaxMsg.setMessage("服务器错误请重试");
        }
        return ajaxMsg;
    }

    @RequestMapping("/to-share")
    @ResponseBody
    public AjaxMsg toShare(String id) {
        AjaxMsg ajaxMsg = new AjaxMsg();
        Map<String, Object> params = Maps.newHashMap();
        try {
            params.put("id", id);
            Customer tmp = customerService.queryByParams(params).get(0);
            tmp.setType(1);
            tmp.setDistributorId("-1");
            customerService.update(tmp);
        } catch (Exception e) {
            ajaxMsg.setCode("500");
            ajaxMsg.setMessage("服务器错误请重试");
        }
        return ajaxMsg;
    }


    @RequestMapping("audit")
    @ResponseBody
    @SystemControllerLog(description = "审核分销商")
    public AjaxMsg audit(String id, String type) {
        AjaxMsg ajaxMsg = new AjaxMsg();
        try {

            Customer customer = customerService.getById(id);
            if (customer != null && type.equals(Constants.CUSTOMER_AUTH_STATUS_AUTHED)) {
                customer.setAuth(Constants.CUSTOMER_AUTH_STATUS_AUTHED);
                List<Dictionary> list = dictionaryService.getDicByKeyNo("AUTH_SUCCESS");
                if (!list.isEmpty() && list.size() > 0) {
                    int smsId=Integer.parseInt(list.get(0).getCaption().toString());
                    customerService.sendSms(customer.getMobilePhone(),null,smsId);
                }
            } else if (customer != null && type.equals(Constants.CUSTOMER_AUTH_STATUS_NOPASS)) {
                customer.setAuth(Constants.CUSTOMER_AUTH_STATUS_NOPASS);
                List<Dictionary> list = dictionaryService.getDicByKeyNo("AUTH_FAIL");
                if (!list.isEmpty() && list.size() > 0) {
                    int smsId=Integer.parseInt(list.get(0).getCaption().toString());
                    customerService.sendSms(customer.getMobilePhone(),null,smsId);
                }
            }
            customerService.update(customer);
            ajaxMsg.setMessage("操作成功。");
            ajaxMsg.setCode(AjaxMsg.SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            ajaxMsg.setCode(AjaxMsg.FAILURE);
            ajaxMsg.setMessage("操作失败");
        }
        return ajaxMsg;
    }

    @RequestMapping("getAuthImg")
    @ResponseBody
    public AjaxMsg getAuthImg(String valueId) {
        AjaxMsg ajaxMsg = new AjaxMsg();
        try {
            Map map = new HashMap();
            map.put("customerId", valueId);
            List<AuthImg> list = authImgService.queryByParam(map);
            ajaxMsg.setDatas(list);
            ajaxMsg.setCode(AjaxMsg.SUCCESS);
        } catch (Exception e) {
            e.printStackTrace();
            ajaxMsg.setCode(AjaxMsg.FAILURE);
            ajaxMsg.setMessage("查询图片失败");
        }
        return ajaxMsg;
    }
}
